<?php

namespace app\admin\controller;

use think\Lang;
use app\common\model\Goodsclass;
use think\Request;
use think\Session;

class Service extends AdminControl
{

    const EXPORT_SIZE = 1000;

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/service.lang.php');
    }

    #服务单列表
    public function index()
    {
        $order_model = model('service');
        $condition = array();

        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['ds_s_order.order_sn'] = $order_sn;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))) {
            $condition['ds_s_order.order_state'] = $order_state;
        }

        $order_type = input('param.order_type');
        if (in_array($order_type, array('1', '2', '3', '4'))) {
            $condition['ds_s_order.order_type'] = $order_type;
        }

        $order_source = input('param.order_source');
        if (in_array($order_source, array('0', '1', '2'))) {
            $condition['ds_s_order.order_source'] = $order_source;
        }

        $invite_store_name = input('param.invite_store_name');
        if ($invite_store_name) {
            $condition['m.invite_store_name'] = $invite_store_name;
        }

        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['ds_s_order.member_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['ds_s_order.add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }

        $condition['is_doubt_order'] = 0; #不是疑难单
        $condition['service_type'] = 0; #主单
        $condition['order_state'] = ['neq', 1]; #1 待审核

        $order_list = $order_model->getapp_OrderList($condition, 10);
        foreach ($order_list as $key => $val) {
            $order_list[$key]['demolition'] = false;
            if ($val['order_state'] == 1) {
                $num = db('s_order_detail')->where('order_id', $val['order_id'])->count();
                if ($num > 1) {
                    $order_list[$key]['demolition'] = true;
                }
            }
            if ($val['parent_id'] == 0) {
                $order_list[$key]['order_types'] = '主单';
            } else {
                $order_list[$key]['order_types'] = '追加单';
            }
        }

        $this->assign('show_page', $order_model->page_info->render());
        $this->assign('order_list', $order_list);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('order_type', ['1' => '安装', '2' => '维修', '3' => '移机', '4' => '保养']);
        $this->assign('order_source', ['0' => '客户', '1' => '商城', '2' => '项目定制']);
        $this->assign('service_type', ['0' => '主单', '1' => '追加单']);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('index');

        return $this->fetch('index');
    }

    #疑难单列表
    public function difficult()
    {
        $order_model = model('service');
        $condition = array();

        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['ds_s_order.order_sn'] = $order_sn;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))) {
            $condition['ds_s_order.order_state'] = $order_state;
        }

        $order_type = input('param.order_type');
        if (in_array($order_type, array('1', '2', '3', '4'))) {
            $condition['ds_s_order.order_type'] = $order_type;
        }

        $invite_store_name = input('param.invite_store_name');
        if ($invite_store_name) {
            $condition['m.invite_store_name'] = $invite_store_name;
        }

        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['ds_s_order.member_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['ds_s_order.add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }

        $condition['is_doubt_order'] = 1; #疑难DNA

        $order_list = $order_model->getapp_OrderList($condition, 10);
        foreach ($order_list as $key => $val) {
            $order_list[$key]['demolition'] = false;
            if ($val['order_state'] == 1) {
                $num = db('s_order_detail')->where('order_id', $val['order_id'])->count();
                if ($num > 1) {
                    $order_list[$key]['demolition'] = true;
                }
            }
            if ($val['parent_id'] == 0) {
                $order_list[$key]['order_types'] = '主单';
            } else {
                $order_list[$key]['order_types'] = '追加单';
            }
        }

        $this->assign('show_page', $order_model->page_info->render());
        $this->assign('order_list', $order_list);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('order_type', ['1' => '安装', '2' => '维修', '3' => '移机', '4' => '保养']);
        $this->assign('order_source', ['0' => '客户', '1' => '商城', '2' => '项目定制']);
        $this->assign('service_type', ['0' => '主单', '1' => '追加单']);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('difficult');

        return $this->fetch('difficult');
    }

    /**
     * Notes:服务单待审核
     * User: shen
     * Date: 2020/5/9
     * Time: 19:09
     * @return mixed
     * @throws \think\Exception
     */
    public function approval()
    {

        $order_model = model('service');
        $condition = array();

        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['ds_s_order.order_sn'] = $order_sn;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))) {
            $condition['ds_s_order.order_state'] = $order_state;
        }
        $order_type = input('param.order_type');
        if (in_array($order_type, array('1', '2', '3', '4'))) {
            $condition['ds_s_order.order_type'] = $order_type;
        }

        $invite_store_name = input('param.invite_store_name');
        if ($invite_store_name) {
            $condition['m.invite_store_name'] = $invite_store_name;
        }

        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['ds_s_order.member_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['ds_s_order.add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }

        #追加设备筛选条件
        $condition['parent_id'] = array('eq', 0);
        $condition['order_state'] = 1;

        $order_list = $order_model->getapp_OrderList($condition, 10);
        foreach ($order_list as $key => $val) {
            $order_list[$key]['demolition'] = false;
            if ($val['order_state'] == 1) {
                $num = db('s_order_detail')->where('order_id', $val['order_id'])->count();
                if ($num > 1) {
                    $order_list[$key]['demolition'] = true;
                }
            }
        }

        $this->assign('show_page', $order_model->page_info->render());
        $this->assign('order_list', $order_list);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('order_type', ['1' => '安装', '2' => '维修', '3' => '移机', '4' => '保养']);
        $this->assign('order_source', ['0' => '客户', '1' => '商城', '2' => '项目定制']);
        $this->assign('service_type', ['0' => '主单', '1' => '追加单']);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('approval');
        return $this->fetch('approval');
    }


    #追加设备申请
    public function additional()
    {

        $order_model = model('service');
        $condition = array();

        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['ds_s_order.order_sn'] = $order_sn;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))) {
            $condition['ds_s_order.order_state'] = $order_state;
        }
        $order_type = input('param.order_type');
        if (in_array($order_type, array('1', '2', '3', '4'))) {
            $condition['ds_s_order.order_type'] = $order_type;
        }

        $invite_store_name = input('param.invite_store_name');
        if ($invite_store_name) {
            $condition['m.invite_store_name'] = $invite_store_name;
        }

        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['ds_s_order.member_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['ds_s_order.add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }

        #追加设备筛选条件
        $condition['parent_id'] = array('gt', 0);
        $condition['order_state'] = ['in','1,2,6'];

        $order_list = $order_model->getapp_OrderList($condition, 10 , '' , '',array('add_time desc'));
        foreach ($order_list as $key => $val) {
            $order_list[$key]['demolition'] = false;
            if ($val['order_state'] == 1) {
                $num = db('s_order_detail')->where('order_id', $val['order_id'])->count();
                $order_list[$key]['part_num'] = $num;
                if ($num > 1) {
                    $order_list[$key]['demolition'] = true;
                }
            }
            $parent_info = db('s_order')->find($val['parent_id']);
            $order_list[$key]['order_sn'] = $parent_info['order_sn'];
        }

        $this->assign('show_page', $order_model->page_info->render());
        $this->assign('order_list', $order_list);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '审核通过', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('order_type', ['1' => '安装', '2' => '维修', '3' => '移机', '4' => '保养']);
        $this->assign('order_source', ['0' => '客户', '1' => '商城', '2' => '项目定制']);
        $this->assign('service_type', ['0' => '主单', '1' => '追加单']);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('additional');
        return $this->fetch('additional');
    }


    #追加工时申请  （追加工时再派单之后操作）
    public function during()
    {

        $order_model = model('service');
        $condition = array();

        $order_sn = input('param.order_sn');
        $originator_name = input('param.originator_name');

        if ($order_sn) {
            $condition['so.order_sn'] = $order_sn;
        }
        if ($originator_name) {
            $condition['soa.originator_name'] = $originator_name;
        }
        $order_type = input('param.order_type');
        if (in_array($order_type, array('1', '2', '3', '4'))) {
            $condition['so.order_type'] = $order_type;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '1', '2'))) {
            $condition['soa.audit_status'] = $order_state;
        }

        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['soa.created_at'] = array('between', array($start_unixtime, $end_unixtime));
        }

        $order_list = $order_model->getapp_HoursList($condition, 10);
        foreach ($order_list as $key => $val) {
            $order_list[$key]['demolition'] = false;
            if ($val['order_state'] == 1) {
                $num = db('s_order_detail')->where('order_id', $val['order_id'])->count();
                if ($num > 1) {
                    $order_list[$key]['demolition'] = true;
                }
            }
        }

        $this->assign('show_page', $order_model->page_info->render());
        $this->assign('order_list', $order_list);

        $this->assign('order_state', ['0' => '待审核', '1' => '审核通过', '2' => '审核失败']);

        $this->assign('order_type', ['1' => '安装', '2' => '维修', '3' => '移机', '4' => '保养']);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('during');
        return $this->fetch('during');
    }

    #主单编辑
    public function service_edit()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $order_id = $data['order_id'];
            $order_info = db('s_order')->where(['order_id' => $order_id])->find();

            $update_data['appoint_phone'] = $data['appoint_phone'];
            $update_data['appointment_time'] = $data['start_time'];
            $update_data['appoint_address'] = $data['appoint_address'];
            $update_data['appoint_detail_address'] = $data['appoint_detail_address'];
            $update_data['appoint_province'] = $data['appoint_province'];
            $update_data['appoint_city'] = $data['appoint_city'];
            $update_data['appoint_district'] = $data['appoint_district'];
            $update_data['remarks'] = $data['remarks'];

            if (empty($data['appoint_address'])) {
                $update_data['appoint_address'] = $order_info['appoint_address'];
            }
            if (empty($data['appoint_detail_address'])) {
                $update_data['appoint_detail_address'] = $order_info['appoint_detail_address'];
            }

            $res = db('s_order')->where(['order_id' => $order_id])->update($update_data);

            $this->updateEditTime($order_id);
            dsLayerOpenSuccess('编辑成功');
        }

        $order_id = intval(input('param.service_id'));

        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $order_model = model('service');
        $order_info = $order_model->getServiceOrderInfo($order_id);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '迁移机单', '4' => '保养单']);
        $this->assign('order_info', $order_info);
        return $this->fetch('service_edit');
    }

    #主单退款
    public function service_refund()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $updata_data = [
                'refund_amount' => $data['refund_amount'],
                'order_state' => 5
            ];
            db('s_order')->where(['order_id' => $data['order_id']])->update($updata_data);
            $this->updateEditTime($data['order_id']);
            dsLayerOpenSuccess('操作成功');
        }
        $order_id = intval(input('param.service_id'));

        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $order_model = model('service');
        $order_info = $order_model->getServiceOrderInfo($order_id);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '迁移机单', '4' => '保养单']);
        $this->assign('order_info', $order_info);
        $this->assign('order_id', $order_id);
        return $this->fetch('service_refund');
    }


    #工时费审核
    public function during_examine()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $order_id = $data['order_id']; #主订单id
            $hour_id = $data['hour_id']; #追加工时的id

            #获取追加的信息
            $append_hours = db('s_order_append')->where(['id' => $hour_id])->find();

            $updata_data['payper_hour'] = $data['payper_hour'];
            $updata_data['audit_status'] = $data['order_state'];

            #审核成功
            if ($data['order_state'] == 1) {
                $updata_data['status'] = 1;
            }

            #审核失败
            if ($data['order_state'] == 2) {
                $updata_data['fail_reason'] = $data['examine_failed_reason'];
            }

            if (!empty($data['payper_hour'])) {
                $updata_data['hours_total'] = $data['payper_hour'] * $append_hours['add_hours'];
            }
            $res = db('s_order_append')->where(['id' => $hour_id])->update($updata_data);


            //更新给服务人员的总价  审核通过的话
            if ($data['order_state'] == 1) {
                $order_info = db('s_order')->where(['order_id' => $order_id])->find();
                $new_data['assign_mechanic_total'] = $order_info['assign_mechanic_total'] + ($data['payper_hour'] * $append_hours['add_hours']);
                $new_data['order_amount'] = $order_info['order_amount'] + ($data['payper_hour'] * $append_hours['add_hours']);
                $new_data['work_master_hous'] = $order_info['work_master_hous'] + $append_hours['add_hours']; #合计的总工时
                $new_data['work_master_price'] = $order_info['work_master_price'] + ($append_hours['add_hours'] * $data['payper_hour']); #合计的工时总价格
                db('s_order')->where(['order_id' => $order_id])->update($new_data);

                //更新给服务人员的总价
                $mechanic_info = db('s_order_mechanic')->where(['order_id' => $order_id])->select();
                foreach ($mechanic_info as $k => $v) {
                    $service_money = $v['service_money'] + ($data['payper_hour'] * $append_hours['add_hours']);
                    db('s_order_mechanic')->where(['id' => $v['id']])->update(['service_money' => $service_money]);
                }
                #推送
                $member_info = db('member')
                    ->where(['member_id' => $order_info['member_id']])
                    ->find();

                #通知内容
                $notif_data = [
                    'order_id' => $order_id,
                    'notif_title' => '订单通知',
                    'notif_content' => '追加工时申请已审核，请及时支付！',
                    'member_id' => $order_info['member_id'],
                    'member_name' => $order_info['member_name'],
                ];
                model('points')->saveAfficeslog(2, 0, $notif_data); #客户
                pushMessageToSingle('追加工时通知', $member_info['clientid'], '追加工时申请已审核，请及时支付！');
            }

            if ($res) {
                // $this->totalAmount($order_id);
                dsLayerOpenSuccess('设置成功');
            } else {
                $this->error('设置失败');
            }
        }

        $order_id = intval(input('param.order_id')); #主订单id
        $hour_id = intval(input('param.hour_id')); #追加工时的id

        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $order_model = model('service');
        $order_info = $order_model->getServiceOrderHourInfo($order_id, $hour_id);

        $service_info = $order_model->getServiceOrderInfo($order_id);
        $this->assign('son_order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '支付完成', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已接单', '9' => '派单中']);
        //订单变更日志
        //        $log_list = $order_model->getOrderlogList(array('order_id' => $order_info['order_id']));
        //        $this->assign('order_log', $log_list);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '迁移机单', '4' => '保养单']);
        $this->assign('order_info', $order_info);
        $this->assign('service_info', $service_info);

        return $this->fetch('during_examine');
    }

    /**
     * Notes:子订单详情
     * User: shen
     * Date: 2020/5/9
     * Time: 19:17
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function show_detail()
    {
        $id = intval(input('param.id'));
        if ($id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $goodItem = db('s_order_detail')
            ->alias('d')
            ->join('s_order_image i', 'i.order_detail_id = d.id', 'left')
            ->join('s_order s', 's.order_id = d.order_id', 'left')
            ->field('d.*, i.src,s.parent_id,s.assign_mechanic_name,s.order_type')
            ->where('d.id', $id)
            ->find();


        $goodItem['option_info'] = json_decode($goodItem['option_info'], true);
        $goodItem['parts'] = db('s_order_parts')
            ->alias('p')
            ->join('goods g', 'p.good_id = g.goods_id')
            ->where('p.detail_order_id', $goodItem['id'])
            ->field('p.*, g.goods_name')
            ->select();
        if ($goodItem['src']) {
            $goodItem['science_pics'] = explode(',', $goodItem['src']);
        } else {
            $goodItem['science_pics'] = [];
        }
        $this->assign('select', ['0' => '未选择', '1' => '已选择']);
        $this->assign('status', ['0' => '不需要', '1' => '需要']);
        $this->assign('disma_status', ['1' => '拆移', '2' => '安装', '3' => '拆移+安装']);
        $this->assign('goodItem', $goodItem);
        return $this->fetch('show_detail');
    }

    #追加设备 的 子订单详情
    public function append_show_detail()
    {
        $id = intval(input('param.id'));
        if ($id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $goodItem = db('s_order_detail')
            ->alias('d')
            ->join('s_order_image i', 'i.order_detail_id = d.id', 'left')
            ->join('s_order s', 's.order_id = d.order_id', 'left')
            ->field('d.*, i.src,s.assign_mechanic_name,s.order_type,s.order_state,s.examine_failed_reason')
            ->where('d.id', $id)
            ->find();
        // if(!empty($goodItem['type_model'])){
        //    $goodItem['type_model'] = implode(' | ',unserialize($goodItem['type_model']));
        // }

        $goodItem['option_info'] = json_decode($goodItem['option_info'], true);
        $goodItem['parts'] = db('s_order_parts')
            ->alias('p')
            ->join('goods g', 'p.good_id = g.goods_id')
            ->where('p.detail_order_id', $goodItem['id'])
            ->field('p.*, g.goods_name')
            ->select();
        if ($goodItem['src']) {
            $goodItem['science_pics'] = explode(',', $goodItem['src']);
        } else {
            $goodItem['science_pics'] = [];
        }

        $this->assign('select', ['0' => '未选择', '1' => '已选择']);
        $this->assign('status', ['0' => '不需要', '1' => '需要']);
        $this->assign('goodItem', $goodItem);
        return $this->fetch('append_show_detail');
    }

    #拒单、取消订单详情
    public function show_refuse_detail()
    {
        $id = intval(input('param.id'));
        if ($id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $goodItem = db('s_order_mechanic')
            ->alias('d')
            ->join('s_order s', 's.order_id = d.order_id', 'left')
            ->where('d.id', $id)
            ->find();


        $this->assign('select', ['0' => '未选择', '1' => '已选择']);
        $this->assign('status', ['0' => '不需要', '1' => '需要']);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('order_source', ['0' => '客户', '1' => '商城', '2' => '项目定制']);
        $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '迁移机单', '4' => '保养单']);
        $this->assign('order_info', $goodItem);
        return $this->fetch('show_refuse_detail');
    }

    /* 
      大订单获取小订单列表
     */
    public function show()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $order_model = model('service');
        $order_info = $order_model->getServiceOrderInfo($order_id);
        $order_mechanics = db('s_order_mechanic')
            ->alias('s')
            ->join('fuwu_personal p', 's.merid = p.id')
            ->field('s.*,p.name,p.phone')
            ->where('order_id', $order_id)
            ->order('s.id', 'desc')
            ->select();
        $appends = db('s_order_append')
            ->where('order_id', $order_id)
            ->select();
        foreach ($appends as $key => $value) {
            $appends[$key]['hours_total'] = $value['add_hours'] * $value['payper_hour'];
        }

        $app_order_info = db('order')->where(['order_id' => $order_info['order_mall_id']])->find();

        $this->assign('appends', $appends);
        $this->assign('order_mechanics', $order_mechanics);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);;
        $this->assign('son_order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '支付完成', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已接单', '9' => '派单中']);
        $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '迁移机单', '4' => '保养单']);
        $this->assign('order_info', $order_info);
        $this->assign('app_order_mall_id', $app_order_info['apporder_id']);
        $this->assign('status', ['0' => '未接单', '1' => '已接单', '2' => '已拒单', '3' => '已完成', '4' => '已取消', '5' => '待派单', '6' => '已更换']);
        $this->assign('appendStatus', ['0' => '未支付', '1' => '待支付', '2' => '已支付', '3' => '已取消', '4' => '已作废']);
        $this->assign('order_source', ['0' => '客户', '1' => '商城', '2' => '项目定制']);

        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);
        if ($order_info['order_state'] == 4) {
            if ($order_info['imgs']) {
                $imgs_array = explode(',', $order_info['imgs']);
                $this->assign('imgs_array', $imgs_array);
            }
        }

        return $this->fetch('show');
    }

    /**
     * Notes:主服务单审核   7 900 1000  200
     * User: shen
     * Date: 2020/5/9
     * Time: 19:13
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function examine()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $order_id = $data['order_id'];  #主单id

            #主单详情
            $order_info = db('s_order')->where('order_id', $order_id)->find();

            $member_info = db('member')
                ->where(['member_id' => $order_info['member_id']])
                ->find();

            //判断是否设置了工时费
            $detail_info = db('s_order_detail')->where(['order_id' => $order_id])->select();

            //把所有配件金额累加，
            $work_master_hous = 0; #总服务工时
            $count_service_hour_fee = 0; #总的服务人员工时费
            $count_master_hour_fee = 0; #总的工时费用
            $count_customer_part_price = 0; #客户需要支付的配件总金额
            foreach ($detail_info as $k => $v) {
                $order_part_info = db('s_order_parts')->where(['detail_order_id' => $v['id']])->select();
                foreach ($order_part_info as $kk => $vv) {
                    $count_customer_part_price += ($vv['sale_part_price'] * $vv['num']);
                }
                $work_master_hous += $v['need_hours'];
                $count_service_hour_fee += ($v['fuwu_hour'] * $v['need_hours']);
                $count_master_hour_fee += ($v['payper_hour'] * $v['need_hours']);
            }
            if ($data['order_state'] == 2) {
                #审核通过
                //把订单总价格加上配件费用重新计算了一遍，上门费，服务内容，备注   更新到主单里面
                $update_data = [
                    'order_state' => 2,
                    'door_fee' => $data['door_fee'],
                    'service_content' => $data['service_content'],
                    'manager_remark' => $data['manager_remark'],
                    #(服务人员总费用) 上门费用+ 工时*给服务人员的价格,接单之后选择配件才算配件费
                    'assign_mechanic_total' => (float) $order_info['assign_mechanic_total'] + (float) $data['door_fee'] + (float) $count_service_hour_fee,
                    'count_part_price' => $count_customer_part_price,
                    'work_master_hous' => $work_master_hous,
                    'work_master_price' => $count_master_hour_fee
                ];
                #通知内容
                $notif_data = [
                    'order_id' =>  $order_id,
                    'notif_title' => '服务单通知',
                    'notif_content' =>  '您提交的服务单申请已审核，请及时支付！',
                    'member_id' => $order_info['member_id'],
                    'member_name' => $order_info['member_name'],
                ];
                pushMessageToSingle('服务单通知', $member_info['clientid'], '您提交的服务单申请已审核，请及时支付！');
            } else {
                #审核失败
                $update_data = [
                    'order_state' => 6,
                    'examine_failed_reason' => $data['examine_failed_reason']
                ];
                #通知内容
                $notif_data = [
                    'order_id' =>  $order_id,
                    'notif_title' => '服务单通知',
                    'notif_content' =>  '您提交的服务单申请审核失败，失败原因：' . $data['examine_failed_reason'],
                    'member_id' => $order_info['member_id'],
                    'member_name' => $order_info['member_name'],
                ];
            }

            $res = db('s_order')->where('order_id', $order_id)->update($update_data);

            if ($res) {

                model('points')->saveAfficeslog(2, 0, $notif_data); #客户    

                 $this->totalAmount($order_id);
                $this->updateEditTime($order_id);
                dsLayerOpenSuccess('设置成功');
            } else {
                $this->error('设置失败');
            }
        }
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        //获取是否填写了服务工时
        $detail_info = db('s_order_detail')->where(['order_id' => $order_id])->select();
        $is_have_hours = 0;
        foreach ($detail_info as $k => $v) {
            if ($v['fuwu_hour'] == 0.00) {
                $is_have_hours = 1;
                break;
            }
        }
        $order_model = model('service');
        $order_info = $order_model->getServiceOrderInfo($order_id);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '迁移机单', '4' => '保养单']);
        $this->assign('order_info', $order_info);
        $this->assign('order_id', $order_id);
        $this->assign('is_have_hours', $is_have_hours);

        return $this->fetch('examine');
    }

    /**
     * 追加单  审核  7 100 200 500
     */
    public function append_examine()
    {
        if (request()->isPost()) {
            $data = input('post.');

            $order_id = $data['order_id'];  #追加单id

            #追加单详情
            $order_info = db('s_order')->where('order_id', $order_id)->find();

            #主单详情
            $zhu_order_info = db('s_order')->where('order_id', $order_info['parent_id'])->find();

            //追加单的设备详情
            $detail_info = db('s_order_detail')->where(['order_id' => $order_id])->select();

            $count_customer_part_price = 0; #客户需要支付的配件总金额
            foreach ($detail_info as $k => $v) {
                $order_part_info = db('s_order_parts')->where(['detail_order_id' => $v['id']])->select();
                foreach ($order_part_info as $kk => $vv) {
                    $count_customer_part_price += ($vv['sale_part_price'] * $vv['num']);
                }
            }

            //计算总的服务人员费用，累加到主单上
            $append_need_hous = 0; #当前追加单需要的工时
            $append_service_hour_fee = 0; #当前追加单的服务人员工时费
            $append_master_hour_fee = 0; #收取客户的总工时费用
            $append_customer_part_price = 0; #追加单客户需要支付的配件总金额
            $append_carry_part_price = 0; #追加单服务人员携带配件的总费用
            foreach ($detail_info as $k => $v) {
                $append_need_hous += $v['need_hours'];
                $append_service_hour_fee += ($v['fuwu_hour'] * $v['need_hours']);
                $append_master_hour_fee += ($v['payper_hour'] * $v['need_hours']);
                $order_part_info = db('s_order_parts')->where(['detail_order_id' => $v['id']])->select();
                foreach ($order_part_info as $kk => $vv) {
                    $append_customer_part_price += ($vv['sale_part_price'] * $vv['num']);
                    $append_carry_part_price += ($vv['part_price'] * $vv['num']);
                }
            }

            unset($data['order_id']);

            #判断是否审核通过
            if ($data['order_state'] == 2) {
                #审核通过,首先更新当前追加单的服务人员信息
                $data['assign_mechanic_id'] = $zhu_order_info['assign_mechanic_id'];
                $data['assign_mechanic_name'] = $zhu_order_info['assign_mechanic_name'];
                $data['door_fee'] = $data['door_fee'];
                $data['work_master_hous'] = $append_need_hous;
                $data['order_amount'] = $data['door_fee'] + $append_master_hour_fee + $append_customer_part_price;
                $data['work_master_price'] = $append_master_hour_fee;
                $data['count_part_price'] = $append_customer_part_price;
                $data['service_content'] = $data['service_content'];
                $data['manager_remark'] = $data['manager_remark'];
                $data['assign_mechanic_total'] = $data['door_fee'] + $append_service_hour_fee + $append_carry_part_price;
                db('s_order')->where('order_id', $order_id)->update($data);

                $son_order_info = db('s_order')->where('order_id', $order_id)->find();
                //再更新主单的上门费，给服务人员总费用
                $update_data = [
                    'door_fee' => $zhu_order_info['door_fee'] + $data['door_fee'],
                    'work_master_hous' => $zhu_order_info['work_master_hous'] + $append_need_hous,
                    'work_master_price' => $zhu_order_info['work_master_price'] + $append_master_hour_fee,
                    'count_part_price' => $zhu_order_info['count_part_price'] + $append_customer_part_price,
                    'service_part_price' => $zhu_order_info['service_part_price'] + $append_carry_part_price,
                    'service_content' => $zhu_order_info['service_content'] . $data['service_content'],
                    'manager_remark' => $data['manager_remark'],
                    'order_amount' => $zhu_order_info['order_amount'] + $son_order_info['order_amount'],
                    #主单:服务人员费用==追加单的工时费+上门费+携带配件的费用
                    'assign_mechanic_total' => $zhu_order_info['assign_mechanic_total'] + $data['door_fee'] + $append_service_hour_fee + $append_carry_part_price,
                ];
            } else {
                #审核失败
                $s_order_update_data = [
                    'order_state' => 6,
                    'examine_failed_reason' => $data['examine_failed_reason']
                ];
                db('s_order')->where('order_id', $order_id)->data($s_order_update_data)->update();
            }

            #最后更新所有给服务人员的总价格
            //修改服务人员价格
            $s_order_infos = db('s_order')->find($order_info['parent_id']);
            $mechanic_info = db('s_order_mechanic')->where(['order_id' => $order_info['parent_id']])->select();
            foreach ($mechanic_info as $k => $v) {
                db('s_order_mechanic')->where(['id' => $v['id']])->update(['service_money' => $s_order_infos['assign_mechanic_total']]);
            }

            if ($data['order_state'] == 2) {
                #推送
                $member_info = db('member')
                    ->where(['member_id' => $order_info['member_id']])
                    ->find();
                #通知内容
                $notif_data = [
                    'order_id' => $order_id,
                    'notif_title' => '追加服务单通知',
                    'notif_content' => '您提交的服务单追加申请，请及时支付！',
                    'member_id' => $order_info['member_id'],
                    'member_name' => $order_info['member_name'],
                ];
                model('points')->saveAfficeslog(2, 0, $notif_data); #客户    
                pushMessageToSingle('追加服务单通知', $member_info['clientid'], '您提交的服务单追加申请，请及时支付！');

                #如果有配件推送服务人员
                $is_have_parts = false;
                foreach ($detail_info as $k => $v) {
                    $order_part_info = db('s_order_parts')->where(['detail_order_id' => $v['id'], 'type' => 1])->select();
                    if (!empty($order_part_info)) {
                        $is_have_parts = true;
                        break;
                    }
                }
                if ($is_have_parts) {
                    $fw_info = db('s_order')->alias('so')
                        ->join('fuwu_personal fp', 'fp.id = so.assign_mechanic_id')
                        ->field('fp.id,fp.name,fp.clientid')
                        ->find();
                    $notif_data = [
                        'order_id' => $order_id,
                        'notif_title' => '追加服务单通知',
                        'notif_content' => '追加的设备需要携带配件，请注意查看',
                        'member_id' => $fw_info['id'],
                        'member_name' => $fw_info['name'],
                    ];
                    model('points')->saveAfficeslog(2, 1, $notif_data); #服务
                    pushMessageToSingle('追加服务单通知', $fw_info['clientid'], '追加的设备需要携带配件，请注意查看');
                }
            }
            dsLayerOpenSuccess('设置成功');

        }
        $order_id = intval(input('param.order_id'));

        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        //获取是否填写了服务工时
        $detail_info = db('s_order_detail')->where(['order_id' => $order_id])->select();
        $is_have_hours = 0;
        foreach ($detail_info as $k => $v) {
            if ($v['payper_hour'] == 0.00) {
                $is_have_hours = 1;
                break;
            }
        }

        //追加单，如果选择配件了之后必须设置给服务人员价格
        $is_choice_part = 1; #设置了 
        foreach ($detail_info as $k => $v) {
            $part_info = db('s_order_parts')->where(['detail_order_id' => $v['id']])->select();
            foreach ($part_info as $kk => $vv) {
                if ($vv['part_price'] == 0.00) {
                    $is_choice_part = 0; #未设置
                    break;
                }
            }
            if ($is_choice_part == 0) {
                break;
            }
        }

        $order_model = model('service');
        $order_info = $order_model->getServiceOrderInfo($order_id);
        $s_order_info = db('s_order')->find($order_info['parent_id']);
        $order_info['order_sn'] = $s_order_info['order_sn'];
        //订单变更日志
        //        $log_list = $order_model->getOrderlogList(array('order_id' => $order_info['order_id']));
        //        $this->assign('order_log', $log_list);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '迁移机单', '4' => '保养单']);
        $this->assign('order_info', $order_info);
        $this->assign('is_have_hours', $is_have_hours);
        $this->assign('is_choice_part', $is_choice_part);

        return $this->fetch('append_examine');
    }

    /*
      追加设备的查看详情
     */
    public function additional_show()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $order_model = model('service');
        $order_info = $order_model->getServiceOrderInfo($order_id);
        $s_order_info = db('s_order')->find($order_info['parent_id']);
        $order_info['order_sn'] = $s_order_info['order_sn'];

        $order_mechanics = db('s_order_mechanic')
            ->alias('s')
            ->join('fuwu_personal p', 's.merid = p.id')
            ->field('s.*,p.name,p.phone')
            ->where('order_id', $order_id)
            ->order('s.id', 'desc')
            ->select();
        $appends = db('s_order_append')
            ->where('order_id', $order_id)
            ->select();
        //订单变更日志
        //        $log_list = $order_model->getOrderlogList(array('order_id' => $order_info['order_id']));
        //        $this->assign('order_log', $log_list);
        $this->assign('appends', $appends);
        $this->assign('order_mechanics', $order_mechanics);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('son_order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '支付完成', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已接单', '9' => '派单中']);
        $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '迁移机单', '4' => '保养单']);
        $this->assign('order_info', $order_info);
        $this->assign('status', ['0' => '未接单', '1' => '已接单', '2' => '已拒单', '3' => '已完成', '4' => '已取消', '5' => '待派单', '6' => '已更换']);
        $this->assign('appendStatus', ['1' => '待支付', '2' => '已支付', '3' => '已取消', '4' => '已作废']);

        return $this->fetch('additional_show');
    }

    /**
     * 追加审核里面 生成新服务单
     */
    public function generate_order()
    {
        $order_id = intval(input('param.order_id'));

        if (!empty($order_id)) {
            #生成新服务单
            // 1、生成主单
            $service = db('s_order')->find($order_id);
            unset($service['order_id']);
            $service['order_sn'] = $this->makeOrderSn();
            $service['order_state'] = 1;
            $service['add_time'] = time();
            $service['cancel_reason_name'] = null;
            $service['is_demolition'] = 0;
            $service['examine_failed_reason'] = null;
            $service['parent_id'] = 0;
            $service['service_type'] = 0;
            $service['is_backstage'] = 0;  #是否后台添加
            $newId = db('s_order')->insertGetId($service);
            // 2、生成详情单
            $data = db('s_order_detail')->where(['order_id' => $order_id])->select();
            $detailArr = [];
            foreach ($data as $key => $value) {
                $detailInfo = array(
                    'order_id' => $newId,
                    'goods_id' => $value['goods_id'],
                    'goods_name' => $value['goods_name'],
                    'b_name' => $value['b_name'],
                    'type_model' => $value['type_model'],  #规格型号
                    'option_info' => $value['option_info'],
                    'add_time' => time()
                );
                $detailArr[] = $detailInfo;
            }
            $detailIds = db('s_order_detail')->insertAll($detailArr);
            if ($detailIds) {
                ds_json_encode(10000, '生成成功');
            } else {
                ds_json_encode(10001, '生成失败');
            }
        }
    }


    /**
     * 平台订单删除订单 （作废）
     */
    public function del_mechanic()
    {
        $mechanicId = intval(input('param.id'));
        if ($mechanicId <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $partInfo = db('s_order_mechanic')->where('id', $mechanicId)->find();
        if (empty($partInfo)) {
            ds_json_encode(10001, '操作失败');
        }

        $res = db('s_order_mechanic')->where('id', $mechanicId)->delete();
        if ($res) {
            ds_json_encode(10000, '操作成功');
        }

        ds_json_encode(10001, '操作失败');
    }

    /**
     * 平台订单删除订单 （作废）
     */
    public function del_part()
    {
        $partId = intval(input('param.id'));
        if ($partId <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $partInfo = db('s_order_parts')->where('id', $partId)->find();
        if (empty($partInfo)) {
            ds_json_encode(10001, '操作失败');
        }

        $res = db('s_order_parts')->where('id', $partId)->delete();
        if ($res) {
            ds_json_encode(10000, '操作成功');
        }

        ds_json_encode(10001, '操作失败');
    }

    /**
     * 平台订单删除订单 （作废）   
     */
    public function del_order()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $order_info = db('s_order')->where('order_id', $order_id)->find();
        if (empty($order_info)) {
            ds_json_encode(10001, '操作失败');
        }

        $res = db('s_order')->where('order_id', $order_id)->update(['order_state' => 0]);
        if ($res) {
            $member_info = db('member')->where(['member_id' => $order_info['member_id']])->find();
            #通知内容
            $notif_data = [
                'order_id' => $order_id,
                'notif_title' => '订单通知',
                'notif_content' => '您下的服务单已作废，请及时查看！',
                'member_id' => $order_info['member_id'],
                'member_name' => $order_info['member_name'],
            ];
            model('points')->saveAfficeslog(2, 0, $notif_data); #客户
            pushMessageToSingle('订单通知', $member_info['clientid'], '您下的服务单已作废，请及时查看！');

            $this->updateEditTime($order_id);
            ds_json_encode(10000, '操作成功');
        }

        ds_json_encode(10001, '操作失败');
    }


    public function send()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $service = db('s_order')->find($data['order_id']);
            if ($service['order_state'] != 9) {
                db('s_order')->where('order_id', $data['order_id'])->update(['order_state' => 9]);
            }
            $data['create_at'] = $data['update_at'] = time();

            $mechanicId = db('s_order_mechanic')->insertGetId($data);
            if ($mechanicId) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        } else {
            $order_id = intval(input('param.order_id'));
        }
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $orderInfo = db('s_order')->find($order_id);
        $address = db('address')->find($orderInfo['address_id']);

        $order_mechanics = db('s_order_mechanic')
            ->alias('s')
            ->join('fuwu_personal m', 's.merid = m.id')
            ->field('s.*,m.name,m.phone')
            ->where('order_id', $order_id)
            ->select();
        #找到当前需要派单的服务人员
        $merid_info = db('s_order_mechanic')->where(['order_id' => $order_id, 'status' => 5])->field('id')->select();
        $now_merid_info = array_column($merid_info, 'id');
        $now_merids = '';
        if (!empty($now_merid_info)) {
            $now_merids = implode(',', $now_merid_info);
        }
        $this->assign('now_merids', $now_merids);
        $this->assign('order_mechanics', $order_mechanics);
        $this->assign('order_id', $order_id);
        $this->assign('order', $orderInfo);
        $this->assign('address', $address);
        $this->assign('status', ['0' => '未接单', '1' => '已接单', '2' => '已拒单', '3' => '已完成', '4' => '已取消', '5' => '待派单', '6' => '已更换']);
        return $this->fetch('send');
    }

    //商品管理
    public function projec_goods(Request $request)
    {

        //详情id
        $detail_oid = $request->param('detail_order_id');

        $this->assign('detail_oid', $detail_oid);

        //获取主单id
        $order_info = db('s_order_detail')->where(['id' => $detail_oid])->find();
        $this->assign('order_id', $order_info['order_id']);

        $s_order_info = db('s_order')->where(['order_id' => $order_info['order_id']])->find();
        $this->assign('service_type', $s_order_info['service_type']);

        $goods = db('s_order_parts')
            ->alias('p')
            ->join('goods g', 'g.goods_id = p.good_id')
            ->join('brand b', 'g.brand_id = b.brand_id')
            ->field('p.id , p.part_price  ,p.num pnum,p.good_id,p.type,p.detail_order_id, b.brand_name, g.*,p.sale_part_price')
            ->where(['p.detail_order_id' => $detail_oid]);
        //todo num数据有问题
        $search_goods_name = trim(input('param.search_goods_name'));
        $store_name = trim(input('param.store_name'));

        /**
         * 处理商品分类
         */
        $choose_gcid = ($t = intval(input('param.choose_gcid'))) > 0 ? $t : 0;
        $gccache_arr = model('goodsclass')->getGoodsclassCache($choose_gcid, 3);
        $this->assign('gc_json', json_encode($gccache_arr['showclass']));
        $this->assign('gc_choose_json', json_encode($gccache_arr['choose_gcid']));
        //关键词
        $where = [];

        if ($search_goods_name != '') {
            $where['search_goods_name'] = $search_goods_name;
            $goods->where('g.goods_name', 'like', '%' . $search_goods_name . '%');
        }
        //.供应商名称
        if ($store_name != '') {
            $where['store_name'] = $store_name;
            $goods->where('g.store_name', 'like', '%' . $store_name . '%');
        }

        //品牌
        $b_id = intval(input('param.b_id'));
        if ($b_id > 0) {
            $where['brand_id'] = $b_id;
            $goods->where('g.b_id', $b_id);
        }
        //分类
        if ($choose_gcid > 0) {
            $where['gc_id_' . ($gccache_arr['showclass'][$choose_gcid]['depth'])] = $choose_gcid;
            $goods->where('g.gc_id_' . ($gccache_arr['showclass'][$choose_gcid]['depth']), $choose_gcid);
        }

        $goods_list = $goods->select();
        //        dump($goods->getLastSql());die;
        $this->assign('goods_list', $goods_list);
        // 品牌
        $brand_list = model('brand')->getBrandPassedList(array());

        $this->assign('search', $where);
        $this->assign('brand_list', $brand_list);


        //商品列表
        $this->assign('search_goods_name', $search_goods_name);
        $this->assign('store_name', $store_name);
        $this->assign('ptype', [0 => '不需要', 1 => '需要']);

        return $this->fetch('projec_goods');
    }

    //获取不需要带货的配件
    public function generate_commodity()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        #服务主单表
        $service_main_info = db('s_order')->find($order_id);
        #服务单详情表
        $service_info = db('s_order_detail')->where(['order_id' => $order_id])->select();
        //获取到每个详情下面需要用到哪些不带货的配件
        $part_list = [];
        foreach ($service_info as $k => $v) {
            #获取的当前设备需要带货的配件
            $parts_info = db('s_order_parts')->where(['detail_order_id' => $v['id'], 'type' => 0])->select();
            foreach ($parts_info as $k => $v) {
                $info = db('goods')->alias('g')
                    ->join('brand b', 'b.brand_id = g.brand_id')
                    ->where(['goods_id' => $v['good_id']])->find();
                $goods_info = [
                    'goods_commonid' => $info['goods_commonid'],
                    'goods_image' => $info['goods_image'],
                    'goods_name' => $info['goods_name'],
                    'brand_name' => $info['brand_name'],
                    'store_name' => $info['store_name'],
                    'goods_price' => $info['goods_price'],
                    'part_price' => $v['part_price'],
                    'part_num' => $v['num'],
                ];
                $part_list[] = $goods_info;
            }
        }
        $this->assign('part_list', $part_list);
        $this->assign('order_id', $order_id);
        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);
        return $this->fetch('generate_commodity');
    }

    //生成商品单
    public function create_commodity()
    {
        $order_id = intval(input('param.order_id')); #服务订单表id

        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $order_model = new \app\common\model\Order();

        #服务主单表
        $service_main_info = db('s_order')->find($order_id);

        #服务单详情表
        $service_info = db('s_order_detail')->where(['order_id' => $order_id])->select();

        //获取到每个详情下面需要用到哪些不带货的配件
        $part_list = [];
        foreach ($service_info as $k => $v) {
            #获取的当前设备需要带货的配件
            $parts_info = db('s_order_parts')->where(['detail_order_id' => $v['id'], 'type' => 0])->select();
            foreach ($parts_info as $k => $v) {
                $part_list[] = db('goods')->where(['goods_id' => $v['good_id']])->find();
            }
        }

        #根据店铺id不同分类
        $store_cart_list = $this->_getStoreCartList($part_list);

        //  echo $voucher_price;die;
        $member_info = db('member')->find($service_main_info['member_id']);
        $yys_info = db('store')->where('store_id', $member_info['invite_store_id'])->find();

        foreach ($store_cart_list as $store_id => $goods_list) {
            #1、获取店铺信息
            $store_info = db('store')->where(['store_id' => $store_id])->find();
            if ($store_id == 0) {
                $store_id = 0;
                $store_info['store_name'] = '平台';
            }

            #2、生成商品订单
            $order['order_sn'] = $this->makeOrderSn();
            #订单类型
            $order['order_type'] = 2;
            $order['orderservice_id'] = $order_id;
            $order['pay_sn'] = $service_main_info['pay_sn'];
            $order['buyer_id'] = $service_main_info['member_id'];
            $order['buyer_name'] = $service_main_info['member_name'];
            $order['store_id'] = $store_id;
            $order['store_name'] = $store_info['store_name'];
            $order['add_time'] = time();
            $order['payment_code'] = $service_main_info['payment_code'];
            $order['payment_time'] = $service_main_info['payment_time'];
            $order['order_state'] = 10;
            $order['order_from'] = 1;
            #商品总价
            $order['goods_amount'] = 1;
            #订单总价
            $order['order_amount'] = $service_main_info['order_amount'];
            $order['yys_id'] = $member_info['invite_store_id'];
            $order['yys_name'] = $yys_info['store_name'];;

            $order_mall_id = db('order')->insertGetId($order);

            $order_info['order_id'] = $order_mall_id;

            $order_list[$order_mall_id] = $order_info;

            //3、生成订单扩展表信息  （用于发货）
            $order_common['order_id'] = $order_mall_id;
            $order_common['store_id'] = $store_id;
            // $order_common['reciver_info'] = $service_main_info['reciver_info'];
            // $order_common['reciver_name'] = $service_main_info['reciver_name'];
            // $order_common['reciver_city_id'] = $service_main_info['reciver_city_id'];
            $order_model->addOrdercommon($order_common);


            #4、生成ordergoods
            foreach ($goods_list as $key => $value) {
                $goods_info = db('goods')->where(['goods_id' => $value['goods_id']])->find();

                #商品扩展表
                $ordergoods['order_id'] = $order_mall_id;
                $ordergoods['goods_id'] = $value['goods_id'];
                $ordergoods['goods_name'] = $value['goods_name'];
                $ordergoods['goods_price'] = $goods_info['goods_price'];
                $ordergoods['goods_num'] = 1;
                $ordergoods['goods_image'] = $goods_info['goods_image'];
                $ordergoods['goods_pay_price'] = 0;
                $ordergoods['store_id'] = $store_id;
                $ordergoods['buyer_id'] = $service_main_info['member_id'];
                $ordergoods['goods_pay_price'] = $goods_info['goods_price'];
                $ordergoods_id = db('ordergoods')->insertGetId($ordergoods);
            }
        }
        $service_address_info = db('address')->where(['address_id' => $service_main_info['address_id']])->find();
        #5、生成大订单 
        $order_ids_array = array_keys($order_list);
        $order_ids = implode(',', $order_ids_array);
        $total['order_ids'] = $order_ids;

        $order_goods_info = db('ordergoods')->where('order_id', 'in', $order_ids)->select();

        if (!empty($order_goods_info)) {
            $total['goods_ids'] = implode(',', array_column($order_goods_info, 'goods_id'));
            $total['ordergoods_ids'] = implode(',', array_column($order_goods_info, 'rec_id'));
        }

        $total['price'] = 0;
        $total['goods_prices'] = $service_main_info['order_amount'];  #商品总价
        $total['order_status'] = 1;
        $total['app_order_type'] = 3;
        $total['order_sn'] = time() . '123';
        $total['pay_sn'] = $service_main_info['pay_sn'];
        $total['create_time'] = time();
        $total['user_id'] = $service_main_info['member_id'];
        $total['member_name'] = $service_main_info['member_name'];
        $total['phone'] = $service_address_info['address_tel_phone'];
        $total['user_name'] = $service_address_info['address_realname'];
        $total['user_address'] = $service_address_info['address_detail'];
        $total['app_order_service_id'] = $order_id;

        $Id = db('app_order')->data($total)->insert();

        foreach ($order_ids_array as $k => $v) {
            db('order')->data(['apporder_id' => $Id])->where(['order_id' => $v])->update();
        }
        dsLayerOpenSuccess('生成商品单成功');
    }

    //编辑数量
    public function num(Request $request)
    {

        if (request()->isPost()) {
            $data = input('param.');
            if ($data['num'] == 0) {
                dsLayerOpenSuccess('配件数量不能为0');
            }
            if (isset($data['goods_id'])) {
                unset($data['goods_id']);
            }
            $id = $data['part_id'];
            unset($data['part_id']);
            $result = db('s_order_parts')->where('id', $id)->update($data);
            dsLayerOpenSuccess('编辑成功');
        } else {
            $id = $request->param('part_id');
            $part = db('s_order_parts')->find($id);
            #判断当前订单是否是追加单
            $order_info = db('s_order_parts')->alias('sop')
                ->join('s_order_detail sod', 'sod.id = sop.detail_order_id')
                ->join('s_order so', 'so.order_id = sod.order_id')
                ->field('so.service_type')
                ->where(['sop.id' => $id])
                ->find();
            $is_add = 0; #不是追加单
            if ($order_info['service_type'] == 1) {
                $is_add = 1;
            }
            $this->assign('part_id', $part['id']);
            $this->assign('num', $part['num']);
            $this->assign('part_price', $part['part_price']);
            $this->assign('type', $part['type']);
            $this->assign('is_add', $is_add);

            return $this->fetch();
        }
    }

    //后台追加工时费
    public function append(Request $request)
    {
        if (request()->isPost()) {
            $data = input('param.');
            $data['order_id'] = $data['service_id'];
            $data['status'] = 1;
            $data['audit_status'] = 1;
            unset($data['service_id']);
            $data['created_at'] = $data['updated_at'] = time();
            $data['originator_name'] = Session::get('admin_name');
            $data['hours_total'] = $data['add_hours'] * $data['payper_hour']; #总计
            $result = db('s_order_append')->insertGetId($data);

            #更新主单信息
            $order_info = db('s_order')->where(['order_id' => $data['order_id']])->find();

            $updata_data['order_amount'] = $order_info['order_amount'] + ($data['add_hours'] * $data['payper_hour']); #总价格
            $updata_data['assign_mechanic_total'] = $order_info['assign_mechanic_total'] + ($data['add_hours'] * $data['payper_hour']); #给服务人员的价格
            $updata_data['work_master_hous'] = $order_info['work_master_hous'] + $data['add_hours']; #合计的总工时
            $updata_data['work_master_price'] = $order_info['work_master_price'] + ($data['add_hours'] * $data['payper_hour']); #合计的工时总价格
            $updata_data['update_time'] = time();
            db('s_order')->where(['order_id' => $data['order_id']])->update($updata_data);
            //更新给服务人员的总价
            $mechanic_info = db('s_order_mechanic')->where(['order_id' => $order_info['order_id']])->select();
            foreach ($mechanic_info as $k => $v) {
                $service_money = $v['service_money'] + ($data['add_hours'] * $data['payper_hour']);
                db('s_order_mechanic')->where(['id' => $v['id']])->update(['service_money' => $service_money]);
            }

            #推送
            $member_info = db('member')
                ->where(['member_id' => $order_info['member_id']])
                ->find();

            #通知内容
            $notif_data = [
                'order_id' => $order_info['order_id'],
                'notif_title' => '订单通知',
                'notif_content' => '追加工时申请已审核，请及时支付！',
                'member_id' => $order_info['member_id'],
                'member_name' => $order_info['member_name'],
            ];
            model('points')->saveAfficeslog(2, 0, $notif_data); #客户
            pushMessageToSingle('追加工时通知', $member_info['clientid'], '追加工时申请已审核，请及时支付！');
            if ($result) {
                // $this->totalAmount($data['order_id']); //更新总数

                dsLayerOpenSuccess('服务费用追加成功！');

            }

            dsLayerOpenSuccess('服务费用追加失败！');
        } else {
            $id = $request->param('service_id');
            $append = db('s_order_append')->find($id);
            if (!$append) {
                $append = array(
                    'add_hours' => 0.0,
                    'payper_hour' => 0, 0
                );
            }

            $this->assign('append', $append);

            return $this->fetch();
        }
    }

    /*
     发送服务人员
    */
    public function send_service_person(Request $request)
    {
        if (request()->isPost()) {
            $data = input('post.fuwuIds/a');
            $detail_oid = input('post.oid');
            if (!empty($data)) {
                if (count($data) > 5) {
                    dsLayerOpenSuccessNew('操作失败,不能派给五人以上的服务人员！', '/admin/service/send_service_person.html');
                }
                $num = db('s_order_mechanic')
                    ->where('order_id', $detail_oid)
                    ->where('status', 0)
                    ->count();
                if ((count($data) + $num) > 5) {
                    dsLayerOpenSuccessNew("操作失败,不能派给五人以上的服务人员!您已经设置" . $num . "个服务人员，此次提交" . count($data) . "个", '/admin/service/send_service_person.html');
                }
                $serviceArr = [];
                foreach ($data as $key => $value) {
                    $mechanicInfo = db('s_order_mechanic')
                        ->where('order_id', $detail_oid)
                        ->where('merid', $value)
                        ->where('status', 0)
                        ->find();
                    if ($mechanicInfo) {
                        continue;
                    }
                    $item = [];
                    $item['status'] = 5; #待派单
                    $item['create_at'] = $item['update_at'] = time();
                    $item['order_id'] = $detail_oid;
                    $item['merid'] = $value;
                    $item['admin_id'] = session('admin_id');
                    $item['admin_name'] = session('admin_name');
                    $serviceArr[] = $item;
                }

                if (!$serviceArr) {
                    dsLayerOpenSuccessNew('请勿重复提交服务人员！', '/admin/service/send_service_person.html');
                }
                $mechanicId = db('s_order_mechanic')->insertAll($serviceArr);

                if ($mechanicId) {
                    dsLayerOpenSuccess('操作成功 ！');
                } else {
                    dsLayerOpenSuccessNew('操作失败', '/admin/service/send_service_person.html');
                }
            } else {
                dsLayerOpenSuccessNew('请选择需要导入的服务人员!', '/admin/service/send_service_person.html');
            }
        } else {
            $project_id = input('param.project_id');
            $oid = input('param.oid');
            $where['project_id'] = $project_id;
            $info = db('goodsproject')->where($where)->find();
            unset($where);

            $where = [];
            $this->assign('project_id', $project_id);
            $this->assign('order_id', $oid);

            $info = explode(',', $info['goods_commonid']);
            $this->assign('info', $info);
            $this->assign('search_brand_name', trim(input('param.search_brand_name')));

            $goods_model = model('Fupersonal');
            /**
             * 处理商品分类
             */
            $choose_gcid = ($t = intval(input('param.choose_gcid'))) > 0 ? $t : 0;

            $gccache_arr = model('goodsclass')->getGoodsclassCache($choose_gcid, 3);
            $this->assign('gc_json', json_encode($gccache_arr['showclass']));
            $this->assign('gc_choose_json', json_encode($gccache_arr['choose_gcid']));

            if (!empty(input('param.search_fuwu_name'))) {
                $where['ds_fuwu_personal.name'] = array('like', "%" . input('param.search_fuwu_name') . "%");
            }

            //星期之间   每日之间
            $detail = db('s_order')->find($oid);
            $week = date('w', strtotime($detail['appointment_time']));
            #判断周末
            if ($week == 0) {
                $week = 7;
            }

            $where['ds_fuwu_personal.cardstatus'] = 1; #认证通过的
            $where['ds_fuwu_personal.status'] = 1;

            $where['ds_fuwu_personal.startweek'] = array('<=', $week);
            $where['ds_fuwu_personal.endweek'] = array('>=', $week);

            $hourMin = date('H:i', strtotime($detail['appointment_time']));
            $where['ds_fuwu_personal.starttime'] = array('<=', $hourMin);
            $where['ds_fuwu_personal.endtime'] = array('>=', $hourMin);

            $area = db('address')
                ->alias('a')
                ->join('area e', 'a.area_id=e.areacode')
                ->where('a.address_id', $detail['address_id'])
                ->field('e.area_id,e.area_deep,e.area_parent_id')
                ->find();
            //因为服务端选择工作区域只能到市，需要判断
            if ($area['area_deep'] == 3) { #
                $area = db('area')->where(['area_id' => $area['area_parent_id']])->field('area_id')->find();
            }
            //  $area['area_id'] = 0;

            $field = 'ds_fuwu_personal.id, ds_fuwu_personal.name pname,s.name sname, g.name gname, ds_fuwu_personal.startweek,ds_fuwu_personal.starttime,ds_fuwu_personal.endweek,ds_fuwu_personal.endtime,ds_fuwu_personal.phone';

            $goods_list = $goods_model->getListByTimeAndAddress($where, $field, 100, 'ds_fuwu_personal.gradeid', $area['area_id']);

            /**
             * 查询条件
             */
            $where = array();
            //分类查询
            $search_gc_id1 = input('get.search_gc_id1', '');
            $search_gc_id2 = input('get.search_gc_id2', '');
            $search_gc_id3 = input('get.search_gc_id3', '');
            if ($search_gc_id1) {
                $where['g.gc_id'] = $search_gc_id1;
            }
            if ($search_gc_id2) {
                $where['g2.gc_id'] = $search_gc_id2;
            }
            if ($search_gc_id3) {
                $where['g3.gc_id'] = $search_gc_id3;
            }

            //品牌
            $b_id = intval(input('param.b_id'));
            if ($b_id > 0) {
                $where['brand_id'] = $b_id;
            }

            foreach ($goods_list as $lkey => $item) {
                $field = 'g.gc_name gc1_name,g2.gc_name gc2_name,g3.gc_name gc3_name,b.brand_name,anzhuang,weixiu,baoyang';
                $where['fuwuid'] = $item['id'];

                $jinengs = model('fujineng')->getSearchList($where, $field, 10);
                if (isset($where['brand_id']) || isset($where['g.gc_id']) || isset($where['g2.gc_id']) || isset($where['g3.gc_id'])) {

                    if ($jinengs) {
                        $goods_list[$lkey]['jinengs'] = $jinengs;
                    } else {
                        unset($goods_list[$lkey]);
                    }
                } else {
                    $goods_list[$lkey]['jinengs'] = $jinengs;
                }
            }

            $this->assign('goods_list', $goods_list);
            $this->assign('choose_gcid', $choose_gcid);
            $this->assign('show_page', $goods_model->page_info->render());

            //            $storage_array = $goods_model->calculateStorage($goods_list);
            //            $this->assign('storage_array', $storage_array);

            // 品牌
            $brand_list = model('brand')->getBrandPassedList(array());

            $this->assign('search', $where);
            $this->assign('week', ['1' => '星期一', '2' => '星期二', '3' => '星期三', '4' => '星期四', '5' => '星期五', '6' => '星期六', '7' => '星期日 ']);
            $this->assign('skill_s', [0 => '无', 1 => '了解', 2 => '熟练']);
            $this->assign('brand_list', $brand_list);
            $this->assign('search_goods_name', '');
            $this->assign('store_name', '');
            //三级分类查询
            $class = new Goodsclass();
            $parent_class_list = $class->getGoodsclassList(['gc_parent_id' => 0]);
            $this->assign('class_list', $parent_class_list);
            return $this->fetch();
        }
    }

    #确认派单
    public function send_service_notice(Request $request)
    {
        $order_id = input('param.order_id');
        $now_merids = explode(',', input('param.now_merids')); #当前需要派单的服务人员


        $service = db('s_order')->find($order_id);

        #派单次数
        $distribute_nums = $service['distribute_nums'] + 1;
        db('s_order')->where('order_id', $order_id)->update(['order_state' => 8, 'distribute_nums' => $distribute_nums]);

        foreach ($now_merids as $key => $value) {
            #修改派单状态
            db('s_order_mechanic')->where(['id' => $value])->update(['status' => 0, 'service_money' => $service['assign_mechanic_total']]);
            #推送 + 通知内容
            $mechanicInfo = db('s_order_mechanic')
                ->where('id', $value)
                ->find();
            $service_info = db('fuwu_personal')
                ->where(['id' => $mechanicInfo['merid']])
                ->find();
            $notif_data = [
                'order_id' => $order_id,
                'notif_title' => '服务单通知',
                'notif_content' => '您有新的服务订单，请及时查看！',
                'member_id' => $service_info['id'],
                'member_name' => $service_info['name'],
            ];
            model('points')->saveAfficeslog(2, 1, $notif_data); #服务人员
            pushMessageToSingle('服务单通知', $service_info['clientid'], '您有新的服务订单，请及时查看！');
        }
        #推送给客户
        $member_info = db('member')->where(['member_id' => $service['member_id']])->find();
        $notif_data = [
            'order_id' => $order_id,
            'notif_title' => '订单通知',
            'notif_content' => '您提交的服务订单已派单，请等待服务人员上门服务！',
            'member_id' => $service['member_id'],
            'member_name' => $service['member_name'],
        ];
        model('points')->saveAfficeslog(2, 0, $notif_data); #服务人员
        pushMessageToSingle('订单通知', $member_info['clientid'], '您提交的服务订单已派单，请等待服务人员上门服务！');

        return json(['url' => url('Service/index'), 'code' => 1, 'msg' => '保存成功']);
    }

    /**
     * 服务技能详情
     */
    public function skill_view()
    {
        $model = model('Fujineng');
        $field = 'g.gc_name gc1_name,g2.gc_name gc2_name,g3.gc_name gc3_name,b.brand_name,anzhuang,weixiu,baoyang,ds_fuwu_personal_jineng.brandid';
        $where['fuwuid'] = input('id');
        $where['ds_fuwu_personal_jineng.status'] = 2;

        $jinengs = model('fujineng')->getSearchList($where, $field, 10);

        foreach ($jinengs as $key => $value) {
            $brand = trim($value['brandid'], ',');
            $brand_array = explode(',', $brand);

            foreach ($brand_array as $k => $v) {
                $brand_info = db('brand')->where(['brand_id' => $v])->find();
                $brand_name = $brand_info['brand_name'];
            }
            $jinengs[$key]['brand_name'] = $brand_name;
        }

        $this->assign('id', input('id'));
        $this->assign('jinengs', $jinengs);
        $this->assign('skill_s', [0 => '无', 1 => '了解', 2 => '熟练']);
        return $this->fetch();
    }

    /**
     * @name: xiaozou
     * @title:  配件导入
     * @url:
     * @param {type}
     * @return:
     */
    public function edit_band_goods(Request $request)
    {
        if (request()->isPost()) {
            $data = input('post.goods_id/a');
            $detail_oid = input('post.detail_oid'); #当前设备的详情id

            #获取客户上级的运营商id，如果运营商导入过这件商品，就是运营商销售价格，没导入的话按照提成运营商走
            $detail_info = db('s_order_detail')->alias('sod')
                ->join('s_order so', 'so.order_id = sod.order_id')
                ->field('so.member_id,so.service_type')
                ->where(['sod.id' => $detail_oid])
                ->find();
            $yys_id = get_parent_yys_id($detail_info['member_id']); #运营商id
            if (!empty($data)) {
                foreach ($data as $key => $value) {
                    #筛选掉已经导入过的商品
                    $is_repeat = false; #配件库里没有当前导入的商品
                    $part_list = db('s_order_parts')->where(['detail_order_id' => $detail_oid])->select();
                    foreach ($part_list as $k => $v) {
                        if ($value == $v['good_id']) {
                            $is_repeat = true;
                            break;
                        }
                    }
                    #判断运营商导入过这件商品没
                    if ($is_repeat) {
                        continue;
                    }
                    $goods = db('goods')->where('goods_id', $value)->find();

                    $sale_part_price = 0;
                    if ($yys_id) {
                        $y_goods_info = db('y_goods')->where(['goods_id' => $value, 'store_id' => $yys_id])->find();
                        if ($y_goods_info) {
                            $y_goods_price = empty($y_goods_info['price']) ? 0 : $y_goods_info['price'];
                            $sale_part_price = $goods['gu_final_price'] + $y_goods_price; #加价运营商是销售价
                        } else {
                            $sale_part_price = $goods['ti_final_price']; #默认走提成运营商的售价
                        }
                    }
                    #判断如果是追加单的话，必须选择为带货
                    $carrying_goods = 0;
                    $is_bring_goods = 0;
                    if ($detail_info['service_type'] == 1) {
                        $carrying_goods = 1;
                        $is_bring_goods = 1;
                    }
                    $part = array(
                        'detail_order_id' => $detail_oid,
                        'good_id' => $value,
                        'goods_commonid' => $goods['goods_commonid'],
                        'create_at' => time(),
                        'sale_part_price' => $sale_part_price,
                        'type' => $carrying_goods,
                        'is_bring_goods' => $is_bring_goods
                    );
                    db('s_order_parts')->insert($part);
                }
                $order_info = db('s_order_detail')->find($detail_oid);
                db('s_order')->where(['order_id' => $order_info['order_id']])->update(['is_bring_goods' => 1]);

                dsLayerOpenSuccess('导入成功', url('Service/projec_goods', ['detail_order_id' => $detail_oid]));
            } else {
                dsLayerOpenSuccess('请选择需要导入的商品', url('Service/edit_band_goods'));
            }
        } else {
            $project_id = input('param.project_id');
            $detail_oid = input('param.detail_oid');

            $this->assign('project_id', $project_id);
            $this->assign('detail_oid', $detail_oid);

            $parts_info = db('s_order_parts')->where(['detail_order_id' => $detail_oid])->select();
            $info = [];
            foreach ($parts_info as $key => $value) {
                $info[] = $value['good_id'];
            }
            $this->assign('info', $info);


            if (!empty(input('param.search_brand_name'))) {
                $condition['goods_name'] = array('like', "%" . input('param.search_brand_name') . "%");
            }
            $this->assign('search_brand_name', trim(input('param.search_brand_name')));


            // ------------------------
            $goods_model = model('goods');
            /**
             * 处理商品分类
             */
            $choose_gcid = ($t = intval(input('param.choose_gcid'))) > 0 ? $t : 0;

            $gccache_arr = model('goodsclass')->getGoodsclassCache($choose_gcid, 3);
            $this->assign('gc_json', json_encode($gccache_arr['showclass']));
            $this->assign('gc_choose_json', json_encode($gccache_arr['choose_gcid']));
            /**
             * 查询条件
             */
            $where = array();
            //查询已经审核完成的商品
            $where['goods_lock'] = '0';
            $where['goods_status'] = '1';
            $where['goodscommon.is_two_goods'] = 0;
            //邹建伟
            // $where['goodscommon.goods_commonid'] = ['not in',$info];
            //关键词
            $search_goods_name = trim(input('param.search_goods_name'));
            if ($search_goods_name != '') {
                $where['goods.goods_name'] = array('like', '%' . $search_goods_name . '%');
            }
            //供应商
            $store_name = trim(input('param.store_name'));
            if ($store_name != '') {
                $where['goods.store_name'] = array('like', '%' . $store_name . '%');
            }
            //分类查询
            $search_gc_id1 = input('get.search_gc_id1', '');
            $search_gc_id2 = input('get.search_gc_id2', '');
            $search_gc_id3 = input('get.search_gc_id3', '');
            if ($search_gc_id1) {
                $where['goods.gc_id_1'] = ['eq', $search_gc_id1];
            }
            if ($search_gc_id2) {
                $where['goods.gc_id_2'] = ['eq', $search_gc_id2];
            }
            if ($search_gc_id3) {
                $where['goods.gc_id_3'] = ['eq', $search_gc_id3];
            }

            //品牌
            $b_id = intval(input('param.b_id'));
            if ($b_id > 0) {
                $where['brand_id'] = $b_id;
            }
            //分类
            // if ($choose_gcid > 0) {
            //     $where['gc_id_' . ($gccache_arr['showclass'][$choose_gcid]['depth'])] = $choose_gcid;
            // }

            // $goods_list = $goods_model->getGoodsCommonList($where, '*', 10, 'goods_commonid desc');
            $goods_list = $goods_model->getGoodsUnionListss($where, '*,goods.goods_name as new_goods_name', 'goodscommon.goods_addtime desc');


            $this->assign('goods_list', $goods_list);
            $this->assign('search_goods_name', $search_goods_name);
            $this->assign('store_name', $store_name);
            $this->assign('choose_gcid', $choose_gcid);
            $this->assign('show_page', $goods_model->page_info->render());

            $storage_array = $goods_model->calculateStorage($goods_list);
            $this->assign('storage_array', $storage_array);

            // 品牌
            $brand_list = model('brand')->getBrandPassedList(array());

            $this->assign('search', $where);
            $this->assign('brand_list', $brand_list);

            //三级分类查询
            $class = new Goodsclass();
            $parent_class_list = $class->getGoodsclassList(['gc_parent_id' => 0]);
            $this->assign('class_list', $parent_class_list);
            return $this->fetch();
        }
    }

    private function makeOrderSn()
    {
        $date = date('Ymd');
        $num = $date . '0000' . substr(time(), 3, 7) . rand(1000, 999);

        return $num;
    }

    /**
     * @name: xiaozou
     * @title: 追加设备
     * @url:
     * @param {type}
     * @return:
     */
    public function show_equipments(Request $request)
    {
        if (request()->isPost()) {
            // $data = input('post.goods_commonid/a');  #设备库id
            $service_id = input('post.service_id');  #服务单id
            $order_form = input('post.order_form');  ##在哪追加的设备  1--服务单待审核  2--服务单列表、疑难单列表(待审核追加的设备合并到主单里面)
            $data = input('post.brand_id/a');    #设备库对应的品牌id
            if (!empty($data)) {
                #子订单   追加服务单
                if ($order_form == 2) {
                    $service = db('s_order')->find($service_id);
                    unset($service['order_id']);
                    $service['order_sn'] = $service['order_sn'];
                    $service['order_state'] = 1;
                    $service['add_time'] = time();
                    $service['cancel_reason_name'] = null;
                    $service['is_demolition'] = 0;
                    $service['examine_failed_reason'] = null;
                    $service['parent_id'] = $service_id;
                    $service['service_type'] = 1;
                    $service['is_backstage'] = 0;  #是否后台添加
                    $newId = db('s_order')->insertGetId($service);
                }

                foreach ($data as $key => $value) {
                    $data_array = explode('-----', $value);
                    $equipment = db('new_equipment_brand')->alias('neb')->join('new_equipment ne', 'ne.id=neb.equipment_id')
                        ->where(['equipment_brand_id' => $data_array['0']])->find();  #获取选中的设备库信息

                    $main_order_id = $service_id;
                    if ($order_form == 2) {
                        $main_order_id = $newId;
                    }
                    $detailInfo = array(
                        'order_id' => $main_order_id,
                        'goods_id' => $equipment['id'],
                        'goods_name' => $equipment['goods_name'],
                        'b_name' => $equipment['brand_name'],
                        'type_model' => $equipment['spec_value_type'],  #规格型号
                        'add_time' => time(),
                        'type_model' => '',
                    );

                    if (isset($data_array['1'])) {
                        $detailInfo['type_model'] = $data_array['1'];
                    }

                    $optionIds = input('post.' . $equipment['equipment_id'] . 'options/a');

                    $options = db('equipment_option')->where('equipment_id', $equipment['equipment_brand_id'])->select();
                    $detailOptions = [];
                    foreach ($options as $option) {
                        //如果是维修单保养单可以选择部位，迁移机单选择拆机和安装这部分统一按照部位存储json串进optionCheckInfo
                        $temp = [];
                        $temp['oid'] = $option['id'];
                        $temp['content'] = $option['content'];
                        $temp['selected'] = 1;
                        if (!empty($optionIds) && in_array($option['id'], $optionIds)) {
                            $temp['selected'] = 1;
                        }
                        if(empty($optionIds)){
                            $temp['selected'] = 1; #如果没选择的话，默认为选择
                        }

                        $detailOptions[] = $temp;
                        if ($detailOptions) {
                            $detailInfo['option_info'] = json_encode($detailOptions);
                        }
                    }
                    $detailIds = db('s_order_detail')->data($detailInfo)->insert();
                }

                if ($detailIds) {
                    $this->updateEditTime($service_id);
                    dsLayerOpenSuccess('追加设备成功!');
                } else {
                    dsLayerOpenSuccess('追加设备失败！');
                }
            } else {
                dsLayerOpenSuccess('请选择需要导入的设备');
            }
        }

        $service_id = input('param.service_id');  #服务单id
        $this->assign('service_id', $service_id);

        $order_form = input('param.order_form');  #在哪追加的设备  1--服务单待审核  2--服务单列表、疑难单列表
        $this->assign('order_form', $order_form);
        /**
         * 处理商品分类
         */
        $choose_gcid = ($t = intval(input('param.choose_gcid'))) > 0 ? $t : 0;
        $gccache_arr = model('goodsclass')->getGoodsclassCache($choose_gcid, 3);
        $this->assign('gc_json', json_encode($gccache_arr['showclass']));
        $this->assign('gc_choose_json', json_encode($gccache_arr['choose_gcid']));

        /**
         * 查询条件
         */
        $where = array();
        //关键词
        $search_goods_name = trim(input('param.search_goods_name'));
        if ($search_goods_name != '') {
            $where['goods_name'] = array('like', '%' . $search_goods_name . '%');
        }
        //分类查询
        $search_gc_id1 = input('get.search_gc_id1', '');
        $search_gc_id2 = input('get.search_gc_id2', '');
        $search_gc_id3 = input('get.search_gc_id3', '');
        if ($search_gc_id1) {
            $where['gc_one_id'] = ['eq', $search_gc_id1];
        }
        if ($search_gc_id2) {
            $where['gc_two_id'] = ['eq', $search_gc_id2];
        }
        if ($search_gc_id3) {
            $where['gc_three_id'] = ['eq', $search_gc_id3];
        }

        //品牌
        $b_id = intval(input('param.b_id'));
        if ($b_id > 0) {
            $where['brand_id'] = $b_id;
        }

        $equipmentModel = model('equipment');
        $where['equipment_del'] = 0;
        $where['equipment_status'] = 1;
        $where['status'] = 1;
        $goods_list = $equipmentModel->getNquipmentBrandsList($where, 10);


        $service = db('s_order')->find($service_id); #服务单详情
        foreach ($goods_list as $k => $val) {

            if ($service['order_type'] == 3) {  #拆除
                $goods_list[$k]['options'] = array(
                    array(
                        'id' => 1,
                        'content' => '拆机'
                    ),
                    array(
                        'id' => 2,
                        'content' => '安装'
                    ),
                );
            } elseif (in_array($service['order_type'], [2, 4])) {  #维修 保养
                $options = db('equipment_option')->where('equipment_id', $val['equipment_brand_id'])->select();

                $goods_list[$k]['options'] = $options;
            } else {
                $goods_list[$k]['options'] = [];
            }
            $goods_list[$k]['goods_name'] = $this->subText($val['goods_name'], 20);
        }
        $this->assign('show_page', $equipmentModel->page_info->render());

        $this->assign('goods_list', $goods_list);
        $this->assign('search_goods_name', $search_goods_name);

        // 品牌
        $brand_list = model('brand')->getBrandPassedList(array());
        $this->assign('search', $where);
        $this->assign('brand_list', $brand_list);

        //三级分类查询
        $class = new Goodsclass();
        $parent_class_list = $class->getGoodsclassList(['gc_parent_id' => 0]);
        $this->assign('class_list', $parent_class_list);

        return $this->fetch();
    }

    //验证是否设置工时
    public function ajax_check()
    {
        $order_id = intval(input('param.order_id'));
        $order_detail_info = db('s_order_detail')->where(['order_id' => $order_id])->select();
        $check = true;
        foreach ($order_detail_info as $v) {
            if (empty($v['need_hours'])) {
                $check = false;
                break;
            }
        }
        if ($check) {
            return json(['url' => url('Service/examine'), 'code' => 1]);
        } else {
            return json(['url' => url('Service/examine'), 'code' => 0]);
        }
    }

    /**
     * @do 拆单
     */
    public function demolition(Request $request)
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        if (request()->isPost()) {
            $ids = input('post.chaidanIds/a');
            $num = input('post.num');
            $main = db('s_order')->find($order_id); //主单表
            $mainId = $main['order_id'];
            if (count($ids) != $num) {
                unset($main['order_id']);
                $main['order_state'] = 1;
                $main['order_sn'] = $this->makeOrderSn();
                $main['is_demolition'] = 0;
                $orderId = db('s_order')->insertGetId($main);
                if (!$orderId) {
                    dsLayerOpenSuccess('操作失败！新主单生成失败');
                }
                foreach ($ids as $id) {
                    $status = db('s_order_detail')->where('id', $id)->update(['order_id' => $orderId]);
                    if (!$status) {
                        dsLayerOpenSuccess('操作失败！新子订单生成失败！');
                    }
                }
                $uStatus = db('s_order')->where('order_id', $mainId)->update(['is_demolition' => 0]);
                if (!$uStatus) {
                    dsLayerOpenSuccess('操作失败！原主单拆单失败！');
                }

                $this->totalAmount($mainId);
                $this->totalAmount($orderId);

                dsLayerOpenSuccess('拆单完成！', 'Service/index');
            }

            dsLayerOpenSuccess('拆单失败！不能把所有子订单整体拆出来', 'Service/index');
        }
        //子订单表和主订单表断开联系 由于服务单现场图片表和设备附件表都是和子订单关联，所以只要断开主单和子订单的连接即可。
        $childOrders = db('s_order_detail')->where('order_id', $order_id)->select();
        if (count($childOrders) == 1) {
            db('s_order')->where('order_id', $order_id)->update(['is_demolition' => 0]);
            dsLayerOpenSuccess('操作失败!该单就一个子订单无法拆单！', 'Service/index');
        }
        $this->assign('order_id', $order_id);
        $this->assign('num', count($childOrders));
        $this->assign('childOrders', $childOrders);

        return $this->fetch('demolition');
    }

    /**
     * @do 审核 服务单 设置小订单的单时间的金额和配件
     */
    public function setting()
    {
        if (request()->isPost()) {
            $data = input('post.');

            if (empty($data['need_hours'])) {
                dsLayerOpenSuccess('请设置当前操作工时');
            }

            $order_id = $data['order_id'];  #详情id

            $detailData = array(
                'need_hours' => $data['need_hours'],    #需要的工时数
                'payper_hour' => $data['payper_hour'],  #后台每小时收客户的工时费用
                'fuwu_hour' => $data['fuwu_hour'],       #给服务人员每小时的工时费用
                /*'next_care_time' => $data['next_care_time'] #下次保养时间*/
            );
            db('s_order_detail')->where('id', $order_id)->update($detailData);

            $order = db('s_order_detail')->find($order_id);
            // $this->totalAmount($order['order_id']); //更新总数据
            dsLayerOpenSuccess('操作成功');
        } else {
            $order_id = intval(input('param.detail_order_id'));
        }
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $detail = db('s_order_detail')->find($order_id); //订单详情

        // //获取设备规格型号
        // if(!empty($detail['type_model'])){
        //     $detail['type_model'] = implode(" | ", unserialize($detail['type_model']));
        // }
        $service = db('s_order')->find($detail['order_id']); //服务单总数据
        $equipment = db('equipment')->find($detail['goods_id']); //设备信息
        $parts = db('s_order_parts')
            ->alias('p')
            ->join('goods g', 'p.good_id = g.goods_id')
            ->where('detail_order_id', $order_id)
            ->field('p.*, g.goods_name')
            ->select();
        //计算预计时间
        $time = 0;
        $equipmentOptions = [];
        $options = [];
        // $proposalPriceArr = $this->getProposalPriceByTypeAndAddress($service['address_id']);
        if ($service['address_id']) {
            $address_info = db('address')->where(['address_id' => $service['address_id']])->find();
            if (!$address_info) {
                return json_fail_return('地址不存在');
            }
            $address_area_id = $address_info['area_id'];  #地址的区id
        } else {
            $address_area_id = 0; #地址的区id
        }
        #根据地址计算每小时费用
        $proposalPriceArr = $this->getProposalPriceByTypeAddress($address_area_id);
        switch ($service['order_type']) {
            //1安装  2维修  3拆除  4保养
            case 1: //安装时间
                $time = $equipment['installation_hours'];
                $detail['payper_hour'] = $proposalPriceArr['install_money'];
                break;
            case 3: //迁移机 option

                $options = json_decode($detail['option_info'], true);
                $detail['payper_hour'] = $proposalPriceArr['move_money_price'];
                if (!empty($options)) {
                    foreach ($options as $okey => $option) {
                        if ($option['selected'] == 1) {
                            $options[$okey]['hours'] = '0';
                            if ($option['content'] == '拆机') {
                                $equipmentOptions[] = '拆机';
                                $options[$okey]['hours'] = $equipment['dismantling_hours'];
                                $time = bcadd($time, $equipment['dismantling_hours']);
                            }

                            if ($option['content'] == '安装') {
                                $equipmentOptions[] = '安装';
                                $options[$okey]['hours'] = $equipment['installation_hours'];
                                $time = bcadd($time, $equipment['installation_hours']);
                            }
                        }
                    }
                }
                break;
            case 2:
                $detail['payper_hour'] = $proposalPriceArr['mintain_money_price'];
                $options = json_decode($detail['option_info'], true);
                if (!empty($options)) {
                    foreach ($options as $okey => $option) {
                        $options[$okey]['hours'] = '0';
                        if ($option['selected'] == 1) {
                            $equipmentOptions[] = $option['content'];
                            $repairTime = db('equipment_option')->find($option['oid']);
                            $options[$okey]['hours'] = $repairTime['repair_hours'];
                            $time = bcadd($time, $repairTime['repair_hours']);
                        }
                    }
                }
                break;
            case 4:
                $detail['payper_hour'] = $proposalPriceArr['upkeep_money_price'];
                $options = json_decode($detail['option_info'], true);
                if (!empty($options)) {
                    foreach ($options as $okey => $option) {
                        $options[$okey]['hours'] = '0';
                        if ($option['selected'] == 1) {
                            $equipmentOptions[] = $option['content'];
                            $repairTime = db('equipment_option')->find($option['oid']);
                            $options[$okey]['hours'] = '0';
                            $time = bcadd($time, $repairTime['maintenance_hours']);
                        }
                    }
                }
                break;
        }

        $goods = db('goods')
            ->field('goods_id, goods_name')
            ->where('goods_state', 1)
            ->where('goods_verify', 1)
            ->select();
        foreach ($goods as $key => $good) {
            $goods[$key]['goods_name'] = $this->subText($good['goods_name']);
        }

        $image = db('s_order_image')->where('order_detail_id', $detail['id'])->find();
        if ($image['src']) {
            $detail['science_pics'] = explode(',', $image['src']);
        } else {
            $detail['science_pics'] = [];
        }

        if ($detail['need_hours']) {
            $time = $detail['need_hours'];
        }


        $this->assign('parts', $parts);
        $this->assign('goods', $goods);
        // $this->assign('proposal_price', $proposalPrice);
        $this->assign('time', $time);
        $this->assign('detail', $detail);
        $this->assign('options', $equipmentOptions);
        $this->assign('doptions', $options);
        $this->assign('select', ['0' => '未选择', '1' => '已选择']);
        $this->assign('disma_status', ['1' => '拆移', '2' => '安装', '3' => '拆移+安装']);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '迁移机单', '4' => '保养单']);
        $this->assign('type', ['0' => '不需要', '1' => '需要']);

        return $this->fetch('setting');
    }

    //审核追加单  设置
    public function append_setting()
    {
        if (request()->isPost()) {
            $data = input('post.');

            $order_id = $data['order_id']; #详情id

            $detailData = array(
                'need_hours' => $data['need_hours'],    #需要的工时数
                'payper_hour' => $data['payper_hour'],  #后台每小时收客户的工时费用
                'fuwu_hour' => $data['fuwu_hour'],       #给服务人员每小时的工时费用
                /*'next_care_time' => $data['next_care_time'], #下次保养时间*/
                'diagnostic_results' => $data['diagnostic_results']
            );

            $status = db('s_order_detail')->where('id', $order_id)->update($detailData);

            if ($status) {
                $order = db('s_order_detail')->find($order_id);
                // $this->totalAmount($order['order_id']); //更新总数据
                dsLayerOpenSuccess('操作成功');
            } else {
                dsLayerOpenSuccess('操作失败');
            }
        } else {
            $order_id = intval(input('param.detail_order_id'));
        }
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $detail = db('s_order_detail')->find($order_id); //订单详情

        //获取设备规格型号
        if (!empty($detail['type_model'])) {
            // $detail['type_model'] = implode(" | ", unserialize($detail['type_model']));
            $detail['type_model'] = $detail['type_model'];
        }
        $service = db('s_order')->find($detail['order_id']); //服务单总数据
        $equipment = db('equipment')->find($detail['goods_id']); //设备信息
        $parts = db('s_order_parts')
            ->alias('p')
            ->join('goods g', 'p.good_id = g.goods_id')
            ->where('detail_order_id', $order_id)
            ->field('p.*, g.goods_name')
            ->select();
        //计算预计时间
        $time = 0;
        $equipmentOptions = [];
        $options = [];
        if ($service['address_id']) {
            $address_info = db('address')->where(['address_id' => $service['address_id']])->find();
            if (!$address_info) {
                return json_fail_return('地址不存在');
            }
            $address_area_id = $address_info['area_id'];  #地址的区id
        } else {
            $address_area_id = 0; #地址的区id
        }
        #根据地址计算每小时费用
        $proposalPriceArr = $this->getProposalPriceByTypeAddress($address_area_id);

        // $proposalPriceArr = $this->getProposalPriceByTypeAndAddress($service['address_id']);
        switch ($service['order_type']) {
            //1安装 2 维修 3 拆除 4保养
            case 1: //安装时间
                $time = $equipment['installation_hours'];
                $proposalPrice = $proposalPriceArr['install_money'];
                break;
            case 3: //迁移机 option
                $options = json_decode($detail['option_info'], true);
                $proposalPrice = $proposalPriceArr['move_money_price'];
                if (!empty($options)) {
                    foreach ($options as $okey => $option) {
                        if ($option['selected'] == 1) {
                            $options[$okey]['hours'] = '0';
                            if ($option['content'] == '拆机') {
                                $equipmentOptions[] = '拆机';
                                $options[$okey]['hours'] = $equipment['dismantling_hours'];
                                $time = bcadd($time, $equipment['dismantling_hours']);
                            }

                            if ($option['content'] == '安装') {
                                $equipmentOptions[] = '安装';
                                $options[$okey]['hours'] = $equipment['installation_hours'];
                                $time = bcadd($time, $equipment['installation_hours']);
                            }
                        }
                    }
                }
                break;
            case 2:
                $proposalPrice = $proposalPriceArr['mintain_money_price'];
                $options = json_decode($detail['option_info'], true);
                if (!empty($options)) {
                    foreach ($options as $okey => $option) {
                        $options[$okey]['hours'] = '0';
                        if ($option['selected'] == 1) {
                            $equipmentOptions[] = $option['content'];
                            $repairTime = db('equipment_option')->find($option['oid']);
                            $options[$okey]['hours'] = $repairTime['repair_hours'];
                            $time = bcadd($time, $repairTime['repair_hours']);
                        }
                    }
                }
                break;
            case 4:
                $proposalPrice = $proposalPriceArr['upkeep_money_price'];
                $options = json_decode($detail['option_info'], true);
                if (!empty($options)) {
                    foreach ($options as $okey => $option) {
                        $options[$okey]['hours'] = '0';
                        if ($option['selected'] == 1) {
                            $equipmentOptions[] = $option['content'];
                            $repairTime = db('equipment_option')->find($option['oid']);
                            $options[$okey]['hours'] = '0';
                            $time = bcadd($time, $repairTime['maintenance_hours']);
                        }
                    }
                }
                break;
        }

        $goods = db('goods')
            ->field('goods_id, goods_name')
            ->where('goods_state', 1)
            ->where('goods_verify', 1)
            ->select();
        foreach ($goods as $key => $good) {
            $goods[$key]['goods_name'] = $this->subText($good['goods_name']);
        }

        $image = db('s_order_image')->where('order_detail_id', $detail['id'])->find();
        if ($image['src']) {
            $detail['science_pics'] = explode(',', $image['src']);
        } else {
            $detail['science_pics'] = [];
        }

        if ($detail['need_hours']) {
            $time = $detail['need_hours'];
        }

        $this->assign('parts', $parts);
        $this->assign('goods', $goods);
        $this->assign('proposal_price', $proposalPrice);
        $this->assign('time', $time);
        $this->assign('detail', $detail);
        $this->assign('options', $equipmentOptions);
        $this->assign('doptions', $options);
        $this->assign('select', ['0' => '未选择', '1' => '已选择']);
        $this->assign('order_state', ['-1' => '已取消', '0' => '已作废', '1' => '待审核', '2' => '待支付', '3' => '待派单', '4' => '已完成', '5' => '已退款', '6' => '审核失败', '7' => '进行中', '8' => '已派单', '9' => '派单中', '10' => '大客户已审核', '11' => '大客户待审核', '12' => '大客户审核失败']);
        $this->assign('order_type', ['1' => '安装单', '2' => '维修单', '3' => '迁移机单', '4' => '保养单']);
        $this->assign('type', ['0' => '不需要', '1' => '需要']);

        return $this->fetch('append_setting');
    }

    private function subText($text, $length = 30)
    {
        if (mb_strlen($text, 'utf8') > $length) {
            return mb_substr($text, 0, $length, 'utf8') . '......';
        } else {
            return $text;
        }
    }

    //主单计算
    private function totalAmount($orderId)
    {
        $order = db('s_order')->find($orderId);

        $amount = 0;
        #上门费
        $amount = bcadd($amount, $order['door_fee'], 2);  #上门费求和 (被加数,加数,保留几位小数)
        #工时费
        $details = db('s_order_detail')->where('order_id', $orderId)->select();
        foreach ($details as $detail) {
            $serviceFee = bcmul($detail['need_hours'], $detail['payper_hour'], 2); #精确乘法 求工时费
            $amount = bcadd($amount, $serviceFee, 2);
        }
        #追加工时费
        $appends = db('s_order_append')->where('order_id', $orderId)->select();
        foreach ($appends as $append) {
            $serviceAppend = bcmul($append['add_hours'], $append['payper_hour'], 2);
            $amount = bcadd($amount, $serviceAppend, 2);
        }
        #配件费
        foreach ($details as $detail) {
            $part_info = db('s_order_parts')->where(['detail_order_id' => $detail['id']])->select();
            foreach ($part_info as $v) {
                $part_prices = $v['num'] * $v['sale_part_price'];
                $amount = bcadd($amount, $part_prices, 2);  #上门费求和 (被加数,加数,保留几位小数)
            }
        }

        if (!$order['parent_id']) { //如果不是二级单
            //do 上门费 + 每个detail服务费 + 追加的服务费 + 子订单
            $orders = db('s_order')->where('parent_id', $orderId)->select();
            foreach ($orders as $order) {
                $amount = bcadd($amount, $order['order_amount'], 2);
            }

            db('s_order')->where('order_id', $orderId)->update(['order_amount' => $amount]);
        } else {
            //获取主单   +    获取附单
            db('s_order')->where('order_id', $orderId)->update(['order_amount' => $amount]);

            $this->totalAmount($order['parent_id']); //更新主表数据
        }
    }

    private function updateEditTime($order_id)
    {
        db('s_order')->where(['order_id' => $order_id])->update(['update_time' => time()]);
    }


    //废弃
    private function getProposalPriceByTypeAndAddress($addressId)
    {
        $address = db('address')->find($addressId);
        $price = array(
            "install_area_price" => 0,
            "mintain_money_price" => 0,
            "upkeep_money_price" => 0,
            "move_money_price" => 0,
        );
        if ($address) {
            $addressBills = db('areabill')->where('status', 1)->select();
            $area = db('area')->where('areacode', $address['area_id'])->find();
            if ($addressBills) {
                foreach ($addressBills as $addressBill) {
                    $areaArrs = json_decode($addressBill['area_content'], true);
                    if (!$areaArrs) {
                        continue;
                    } else {
                        foreach ($areaArrs as $areaArr) {
                            $areaIds = explode(',', $areaArr['area_id']);
                            if (in_array($area['area_id'], $areaIds)) {
                                $price = array(
                                    "install_area_price" => $areaArr['install_area_price'],
                                    "mintain_money_price" => $areaArr['mintain_money_price'],
                                    "upkeep_money_price" => $areaArr['upkeep_money_price'],
                                    "move_money_price" => $areaArr['move_money_price']
                                );

                                return $price;
                            }

                            continue;
                        }
                    }
                }

                return $price;
            }

            return $price;
        }

        return $price;
    }

    /**
     * 根据地址计算单价费用
     */
    private function getProposalPriceByTypeAddress($area_id = 0)
    {
        $config_info = db('config')->where('code', 'default_money')->find();
        $money_info = json_decode($config_info['value'], true);

        $aa = 0;
        $money = [
            'install_money' => 0,
            'mintain_money_price' => 0,
            'move_money_price' => 0,
            'upkeep_money_price' => 0
        ];
        if ($area_id) {
            foreach ($money_info['area_content'] as $k => $v) {
                $ids_array = explode(',', $v['area_id']);
                if (in_array($area_id, $ids_array)) {
                    $money['install_money'] = $v['install_area_price'];
                    $money['mintain_money_price'] = $v['mintain_money_price'];
                    $money['move_money_price'] = $v['move_money_price'];
                    $money['upkeep_money_price'] = $v['upkeep_money_price'];
                    $aa = 1;
                }
            }
            if ($aa) {
                #存在
                return $money;
            } else {
                #用默认的
                $money = [
                    'install_money' => (float)$money_info['install_money'],
                    'mintain_money_price' => (float)$money_info['mintain_money_price'],
                    'move_money_price' => (float)$money_info['move_money_price'],
                    'upkeep_money_price' => (float)$money_info['upkeep_money_price'],
                ];
                return $money;
            }
        }
    }

    //根据店铺区分订单
    private function _getStoreCartList($part_list)
    {
        if (empty($part_list) || !is_array($part_list))
            return $part_list;
        $new_array = array();
        foreach ($part_list as $cart) {
            $new_array[$cart['store_id']][] = $cart;
        }
        return $new_array;
    }


    #服务单发票申请
    public function service_invoice_manage()
    {
        $order_model = model('order');
        $condition = array();
        $keyword_type = array('order_sn', 'refund_sn', 'store_name', 'buyer_name', 'goods_name');
        $key = input('get.key');
        $type = input('get.type');
        if (trim($key) != '' && in_array($type, $keyword_type)) {
            $condition[$type] = array('like', '%' . $key . '%');
        }
        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['s_order.order_sn'] = $order_sn;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('1', '2', '3'))) {
            $condition['invoice_type'] = $order_state;
        }

        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['s_order.member_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['s_order.create_time'] = array('between', array($start_unixtime, $end_unixtime));
        }
        // $condition['ds_app_order.is_cancel'] = 0;
        if (isset($condition['s_order.order_status']) && $condition['s_order.order_status'] == 4) {
            $condition['s_order.order_status'] = 1;
            $condition['s_order.refund_price'] = 1;
        }
        $condition['s_order.service_invoice_status'] = 1;
        $condition['invoice_type'] = 3;
        $order_list = $order_model->getServiceInvoiceList($condition, 10);


        //p($refund_list);die;
        $this->assign('show_page', $order_model->page_info->render());
        $this->assign('refund_list', $order_list);
        $this->assign('type', $type);
        $this->assign('query_start_time', $query_start_time);
        $this->assign('query_end_time', $query_end_time);
        $this->setAdminCurItem('service_invoice_manage');
        return $this->fetch('service_invoice_manage');
    }

    /**
     * Notes:设置下次保养时间
     * User: shen
     * Date: 2020/5/22
     * Time: 17:44
     */
    public function edit_time()
    {
        $order_id = input('order_id');
        if (!$order_id) {
            $this->error('操作失败');
        }
        if (request()->isPost()) {
        $update_data = [
            'next_care_time'=>input('post.next_care_time'),
        ];
            $res = db('s_order_detail')->where('id', $order_id)->data($update_data)->update();
            if ($res) {
                dsLayerOpenSuccess('操作成功');
            }else{
                dsLayerOpenSuccess('操作失败');
            }

        } else {

            $order_info = db('s_order_detail')->where('id', $order_id)->find();
            if (!$order_info) {
                $this->error('操作失败');
            }

            if(!$order_info['next_care_time']){
                $order_info['next_care_time'] = date('Y-m-d',time());
            }

            $this->assign('order_info', $order_info);
            return $this->fetch();

        }
    }


    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'index',
                'text' => '服务单列表',
                'url' => url('Service/index')
            ),
            array(
                'name' => 'service_invoice_manage', 'text' => '服务单发票申请', 'url' => url('Service/service_invoice_manage')
            ),
            array(
                'name' => 'difficult',
                'text' => '疑难单列表',
                'url' => url('Service/difficult')
            ),
            array(
                'name' => 'approval',
                'text' => '服务单待审核',
                'url' => url('Service/approval')
            ),
            array(
                'name' => 'additional',
                'text' => '追加设备申请',
                'url' => url('Service/additional')
            ),
            array(
                'name' => 'during',
                'text' => '追加工时申请',
                'url' => url('Service/during')
            ),
        );
        return $menu_array;
    }
}
